package com.ansion.basedb.dao.impl;


import com.ansion.basedb.dao.DaoLoadHelper;
import com.ansion.basedb.dao.UserFTSHelper;
import com.ansion.basedb.dao.model.GroupModel;
import com.ansion.log.VLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Andre on 23-12-27.
 */
public class GroupCachedLogicDaolmpl extends GroupLogicDaoImpl {

	private static final String TAG = "GroupCachedLogicDaolmpl";
	private HashMap<String, GroupModel> groupModelMap = new HashMap<>();
//	private final AtomicBoolean isLoaded = new AtomicBoolean(false);

	@Override
	public void clearCache() {
		synchronized (this) {
			groupModelMap.clear();
			DaoLoadHelper.groupDaoLoadFinish =false;
		}
	}

	@Override
	public List<GroupModel> loadAllGroups() {
		VLog.stopD("APP_START","group inner preload");
		synchronized (this) {
			if (DaoLoadHelper.groupDaoLoadFinish) {
				ArrayList<GroupModel> result = new ArrayList<GroupModel>();

				result.addAll(groupModelMap.values());
				VLog.d("groupCache-->load", result.size()+"");
				VLog.d("groupCache-->load", System.currentTimeMillis()+"");
				return result;
			}
			List<GroupModel> result = super.loadAllGroups();
			if (null == result) {
				result = new ArrayList<GroupModel>();
			}
			groupModelMap.clear();
			for (GroupModel group : result) {
				groupModelMap.put(group.getUid(), group);
			}
			DaoLoadHelper.groupDaoLoadFinish =true;
			VLog.stopD("APP_START","group inner preload end");
			return result;
		}
	}

	@Override
	public GroupModel getGroupModel(String uid) {
		GroupModel mGroupModel;

		synchronized (this) {
			mGroupModel = groupModelMap.get(uid);
			if(!DaoLoadHelper.groupDaoLoadFinish && mGroupModel == null){
				mGroupModel = super.getGroupModel(uid);
				if (null != mGroupModel) {
					groupModelMap.put(mGroupModel.getUid(), mGroupModel);
				}
			}
		}

		return mGroupModel;
	}



	@Override
	public void saveGroup(GroupModel mGroupModel) {

		if(mGroupModel == null){
			return;
		}
		synchronized (this) {

			groupModelMap.put(mGroupModel.getUid(), mGroupModel);
			super.saveGroup(mGroupModel);

		}
	}

	@Override
	public void saveGroup(List<GroupModel> groupList,
			DBOperationCallback callback) {

		synchronized (this) {
			for (GroupModel groupModel : groupList) {
				groupModelMap.put(groupModel.getUid(), groupModel);
			}
			super.saveGroup(groupList, callback);
		}

	}

	@Override
	public void deleteGroup(String gid) {
		GroupModel groupModel;
		synchronized (this) {
			groupModel = groupModelMap.get(gid);
			if(groupModel != null){
				groupModelMap.remove(gid);
			}
			super.deleteGroup(gid);
		}
		UserFTSHelper.deleteGroupAllMembers(gid);
	}


}
